package com.example.exam.service.impl;

import com.example.exam.entity.*;
import com.example.exam.repository.QuestionAnswerRepository;
import com.example.exam.repository.UserRepository;
import com.example.exam.service.ExamPaperService;
import com.example.exam.service.QuestionAnswerService;
import com.example.exam.util.MyArrayUtil;
import com.example.exam.util.QuestionType;
import com.example.exam.vo.InfoVO;
import com.example.exam.vo.QuestionAnalysisVO;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shishuqian
 * date 2021/4/28
 * time 14:28
 **/
@Service
public class QuestionAnswerServiceImpl implements QuestionAnswerService {

    @Autowired
    private QuestionAnswerRepository questionAnswerRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ExamPaperService examPaperService;

    @Override
    public List<String> queryAllAnswerByQuestionId(Integer question_id) {
        return questionAnswerRepository.queryAllAnswerByQuestionId(question_id);
    }

    @Override
    public int countFilledPeople(Integer examPaper_id) {
        return questionAnswerRepository.countFilledPeople(examPaper_id);
    }

    @Override
    public List<QuestionAnalysisVO> countQuestionResult(Integer examPaper_id) {

        //根据试卷id获取此试卷的所有问题
        List<Question> questions = examPaperService.findById(examPaper_id).getQuestionList();

        for(Question question:questions){
            //如果此问题是单选题
            if(question.getQuestionType().equals(QuestionType.DANXUAN)){
                //获取每个问题的选项
                List<Choice> options = question.getChoiceList();
                //记录每个选项被选次数
                double sum = 0;

                //统计所有选项的被选总次数
                for (Choice choice:options){
                    //设置此选项被选次数
                    int count = questionAnswerRepository.countChoice(question.getId(),choice.getId().toString());
                    sum += count;
                }

                //设置选项被选次数和所占百分比
                for(Choice choice:options){
                    int count = questionAnswerRepository.countChoice(question.getId(),choice.getId().toString());
                    choice.setCount(count);

                    if(sum != 0){
                        choice.setPercent(String.format("%.2f",(count/sum)*100)+"%");
                    }else{
                        choice.setPercent("0%");
                    }
                }

            }

            //多选题
            if (question.getQuestionType().equals(QuestionType.DUOXUAN)){
                String[] arr1 = {""};
                List<String> answers = questionAnswerRepository.queryAllAnswerByQuestionId(question.getId());
                double countAnswer = 0;
                for(String answer:answers){
                    answer += "";  //防止答案是null
                    String[] arr2 = answer.split("_");
                    arr1 = MyArrayUtil.ArraysCombine(arr1, arr2);  //将所有的答案放到一个数组里面
                }
                countAnswer = MyArrayUtil.countAllElement(arr1); //答案总数(去除空字符串)

                List<Choice> choices = question.getChoiceList();  //获取此多选题的所有选项
                for (Choice choice:choices){
                    String id = String.valueOf(choice.getId());
                    //判断答案数组里是否包含此选项，不包含说明没人选
                    if (ArrayUtils.contains(arr1,id)){  //包含
                        int countChoice = MyArrayUtil.ArraysElementCount(arr1,id); //统计该选项被选次数
                        choice.setCount(countChoice);
                        choice.setPercent(String.format("%.2f",(countChoice/countAnswer)*100)+"%");
                    }else {
                        choice.setCount(0);
                        choice.setPercent("0%");
                    }
                }
            }

            //判断题
            if (question.getQuestionType().equals(QuestionType.PANDUAN)) {
                String correct = question.getCorrect(); //获取正确答案
                int yesCount = questionAnswerRepository.countChoice(question.getId(),"yes");
                int noCount = questionAnswerRepository.countChoice(question.getId(),"no");
                double sum = yesCount + noCount;
                Choice yesChoice = new Choice();
                Choice noChoice = new Choice();

                if (correct.equals("yes")){
                    yesChoice.setRightAnswer(true);
                }else if (correct.equals("no")){
                    noChoice.setRightAnswer(true);
                }

                yesChoice.setContent("yes");
                noChoice.setContent("no");
                yesChoice.setCount(yesCount);
                noChoice.setCount(noCount);
                //yes,no所占百分比
                if(sum != 0){
                    yesChoice.setPercent(String.format("%.2f",(yesCount/sum)*100)+"%");
                    noChoice.setPercent(String.format("%.2f",(noCount/sum)*100)+"%");
                }else{
                    yesChoice.setPercent("0%");
                    noChoice.setPercent("0%");
                }
                List<Choice> choiceList = new ArrayList<>();
                choiceList.add(yesChoice);
                choiceList.add(noChoice);
                question.setChoiceList(choiceList);
            }


        }

        List<QuestionAnalysisVO> questionAnalysisVOList = new ArrayList<>();

        for (Question question:questions){
            QuestionAnalysisVO questionAnalysisVO = new QuestionAnalysisVO();
            //问题id
            questionAnalysisVO.setQuestionId(question.getId());
            //问题内容
            questionAnalysisVO.setContent(question.getContent());
            //问题类型
            questionAnalysisVO.setQuestionType(question.getQuestionType());
            //问题分数
            questionAnalysisVO.setScore(question.getScore());
            //填空题空数/简答题行数
            questionAnalysisVO.setRowNum(question.getRowNum());
            //问题的选项(判断题的yes和no也放在这里面)
            questionAnalysisVO.setChoiceList(question.getChoiceList());

            questionAnalysisVOList.add(questionAnalysisVO);
        }

        return questionAnalysisVOList;
    }


    @Override
    public int countChoice(Integer question_id,String user_answer) {
        return questionAnswerRepository.countChoice(question_id,user_answer);
    }

    @Override
    public List<InfoVO> queryAllAnswer(Integer questionId) {
        List<QuestionAnswer> questionAnswerList = questionAnswerRepository.queryAllAnswer(questionId);
        List<InfoVO> list = new ArrayList<>();

        for (QuestionAnswer answer: questionAnswerList){
            String userAnswer  = answer.getUserAnswer();
            Integer userId = answer.getUserId();
            User user = userRepository.findById(userId).get();
            String realName = user.getRealName();
            InfoVO vo = new InfoVO(userAnswer,realName);
            list.add(vo);
        }
        return list;
    }

    @Override
    public List<ExamPaperAnswer> viewRanking(Integer examPaperId) {
        List<ExamPaperAnswer> examPaperAnswerList = questionAnswerRepository.viewRanking(examPaperId);
        for (ExamPaperAnswer answer:examPaperAnswerList){
            answer.setQuestionAnswerList(null);
        }
        return examPaperAnswerList;
    }
}
